<template>
  <div class="mobile-editor-wrapper">
    <div class="editor-body">
      <template v-for="(item, index) in editHtml">
        <img-item v-if="item.type === 'img'"
          :size="imgSize"
          :index="index"
          :key="index"
          :imgUrl="item.url"
          @changeData="handleChange"
          @deleteData="handleDelete"/>
        <text-item v-else
          :index="index"
          :key="index"
          :text="item.text"
          @changeText="handleEdit"
          @deleteData="handleDelete"/>
      </template>
    </div>
    <transition name="el-zoom-in-center">
      <div class="input-wrapper" v-show="inputState">
        <div class="input-content">
          <p class="text" v-if="inputMaxLen === 500">单个文本框，字数不得超过<span class="num"> 500</span></p>
          <p class="text" v-else-if="inputMaxLen > 0">即将到达数量上限，此次还可输入<span class="num"> {{inputMaxLen}}</span></p>
          <div class="input-body">
             <x-input v-model="inputText" :validateEvent="!1" :maxlength="inputMaxLen" type="textarea" :rows="4" /> 
          </div>
          <div class="input-footer">
            <el-button class="btn-edit" type="primary" size="small" @click="handleInput">确认</el-button>
            <el-button class="btn-edit" size="small" @click="inputState = !1">取消</el-button>
          </div>
        </div>
      </div>
    </transition>
    <div class="editor-footer">
      <el-col :span="12">
        <img-upload
          :size="imgSize"
          :validateEvent="!1"
          :disabled="uploadState"
          @success="handleSuccess">
          <el-button type="text" class="btn border-r" @click="handleTips">添加图片</el-button>
          <!-- <button type="button" class="btn border-r" @click="handleTips">添加图片</button> -->
        </img-upload>
      </el-col>
      <el-col :span="12">
        <el-button type="text" class="btn" @click="handleEdit('add')">添加文字</el-button>
        <!-- <button type="button" class="btn" @click="handleEdit('add')">添加文字</button> -->
      </el-col>
    </div>
  </div>
</template>

<script>
  import ImgItem from './EditorImgItem'
  import TextItem from './EditorTextItem'
  
  import XInput from 'components/XInput'

  import ImgGroupUpload from 'modules/components/ImgGroupUpload'
  import ImgUpload from 'modules/components/ImgUpload'

  const IMG_SIZE = 1024 * 1024 * 1 // 图片大小
  const MAX_IMG_NUM = 20 // 最多可上传图数量
  const MAX_TEXT_NUM = 10000  // 最多可输入文字数量
  export default{
    components: {
      XInput,
      ImgItem,
      TextItem,
      ImgUpload,
      ImgGroupUpload
    },
    props: {
      value: String,
      isEditor: Boolean
    },
    computed: {
      uploadState () {
        return this.imgNum >= MAX_IMG_NUM
      },
      imgNum () {
        return this.editHtml.filter(item => item.type === 'img').length
      },
      textNum () {
        let num = 0
        this.editHtml.map(item => {
          if (item.type === 'text') {
            num += item.text.length
          }
        })
        return num
      }
    },
    watch: {
      editHtml (nl) {
        let html = ''
        this.editHtml.forEach(item => {
          if (item.type === 'img') {
            html += `<img src="${item.url}" />`
          } else {
            html += `<p>${item.text.replace(/<[^>]+>/g, '')}</p>`
          }
        })
        this.$emit('input', html).$emit('change', html)
      },
      value () {
        if (this.isEditor && this.value && this.isFirst) {
          this.isFirst = !1
          this.initData()
        }
      }
    },
    mounted () {
      // if (this.isEditor) {
      //   this.initData()
      // }
    },
    data () {
      return {
        isFirst: !0, // 初始化编辑
        imgSize: IMG_SIZE,
        imgList: [],
        editHtml: [],
        logoUrl: '',
        inputText: '',
        inputIndex: -1, // 修改文本时需要
        inputState: !1,
        values: '',
        inputMaxLen: 500 // 当前可输入最大字数
      }
    },
    methods: {
      initData () {
        // let isPReg = /^<p>.*<\/p>/i
        let isIReg = /^<img.*\/>/i
        let srcReg = /src=['"]?([^'"]*)['"]?/i
        // let pReg = /<p>(.*)<\/p>/
        let pReg = /^<p>([\s\S]*?)<\/p>$/
        let valReg = /(<p>[^(<p>|</p>)]*<\/p>)|(<img[^(>)]*\/>)/gi
        let valArr = this.value.match(valReg) || []
        valArr.forEach(item => {
          let newItem = ''
          if (isIReg.test(item)) { // 是图片
            let src = item.match(srcReg)[1]
            newItem = {
              type: 'img',
              url: src
            }
          } else { // 文本
            let p = item.match(pReg)[1]
            newItem = {
              type: 'text',
              text: p
            }
          }
          this.editHtml.push(newItem)
        })
      },
      handleTips () {
        // 控制上传状态  如果不可上传则在此处做提示
        if (this.uploadState) {
          this.$message({
            message: '可上传图片数量已达上限20',
            type: 'warning'
          })
        }
        this.inputState = !1 // 关闭编辑模式
      },
      handleSuccess (url) {
        this.editHtml.push({
          type: 'img',
          url: url
        })
      },
      handleEdit (type, data) {
        // 先判断剩余字数
        let remainNum = MAX_TEXT_NUM - this.textNum > 500 ? 500 : MAX_TEXT_NUM - this.textNum
        if (!remainNum) {
          return this.$message({
            message: '可输入字数已达上限10,000',
            type: 'warning'
          })
        }
        // 编辑模式 特殊处理
        if (type === 'edit') {
          this.inputText = data.text
          this.inputIndex = data.index
        } else {
          this.inputIndex = -1
        }
        // 编辑模式 新增模式公共部分
        this.inputState = !0
        this.inputMaxLen = remainNum
      },
      handleInput () {
        // 复原编辑状态
        this.inputState = !1
        // this.inputIndex = -1
        // 过滤编辑的文本  如果内容为空 则不添加 / 不修改
        let resultText = this.inputText.replace(/<|>|"|'/g, '')
        if (!resultText) return
        if (this.inputIndex === -1) {
          this.editHtml.push({
            type: 'text',
            text: resultText
          })
        } else {
          this.$set(this.editHtml, this.inputIndex, {
            type: 'text',
            text: resultText
          })
        }
        this.inputText = ''
      },
      handleChange (index, data) {
        this.$set(this.editHtml, index, data)
      },
      handleDelete (index) {
        this.editHtml.splice(index, 1)
      }
    }
  }
</script>
<style lang="scss">
  .mobile-editor-wrapper{
    .el-upload{
      display: block;
    }
  }
</style>
<style lang="scss" scoped>
  @import '~styles/var.scss';
  .mobile-editor-wrapper{
    position: relative;
    // margin: 15px;
    width: 325px;
    min-width: 325px;
    height: 420px;
    border: 1px solid $border-color-base;
    background-color: $input-background-color;
    .editor-body{
      position: absolute;
      top: 0;
      left: 0;
      bottom: 50px;
      width: 100%;
      padding: 17px 20px;
      overflow-y: auto;
    }
    .editor-footer{
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 50px;
      border-top: 1px solid $border-color-base;
      .img-upload{
        position: relative;
        width: 100%;
        height: 40px;
        background-color: transparent;
        border: none;
        &:hover{
          border: none;
        }
      }
      .btn{
        display: block;
        width: 100%;
        height: 100%;
        padding: 0;
        border: none;
        background: none;
        outline: none;
        line-height: 50px;
        text-align: center;
        color: $six-color;
        cursor: pointer;
        &.border-r{
          border-right: 1px solid $border-color-base;
        }
        &:hover{
          color: $green;
        }
      }
    }
    .input-wrapper{
      .input-content{
        position: absolute;
        top: 0;
        let: 0;
        width: 100%;
        padding:10px;
        background: $background-color;
        .text{
          height: 30px;
          line-height: 28px;
          color: #333;
          font-size: 12px;
          .num{
            color: $orange;
          }
        }
        .input-footer{
          margin:20px 0 10px 0;
          text-align: center;
          .btn-edit{
            width: 62px;
            height: 30px;
          }
        }
      }
    }
  }
</style>
